<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="queryParams.keyword"
          style="margin-bottom:10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="changeValue"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="deptTree"
          node-key="id"
          :data="depts"
          :props="defaultProps"
          default-expand-all
          :expand-on-click-node="false"
          highlight-current
          @current-change="seletNode"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button size="mini" @click="showExcelDialog=true">excel导入</el-button>
          <el-button size="mini" @click="getExecl">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="list">
          <el-table-column label="头像" prop="staffPhoto">
            <template v-slot="{row}">
              <el-avatar v-if="row.staffPhoto">{{ row.staffPhoto }}</el-avatar>
              <span v-else class="username">{{ row.username?.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" />
          <el-table-column
            label="手机号"
            sortable
            prop="mobile"
          />
          <el-table-column label="工号" sortable prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template v-slot="{row}">
              <span v-if="row.formOfEmployment===1"> 正式</span>
              <span v-else-if="row.formOfEmployment===0">非正式</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry" />
          <el-table-column label="操作">
            <template v-slot="{row}">
              <el-button type="text" size="mini" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="mini" @click="btnRole(row.id)">角色</el-button>
              <el-popconfirm title="确认删除该行数据吗？" @onConfirm="confirmDel(row.id)">
                <el-button slot="reference" style="margin-left:10px" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
          small
          layout="prev, pager, next"
          :total="total"
          :page-size="queryParams.pagesize"
          :current-page="queryParams.page"
          @current-change="changePage"
        />
      </div>
    </div>
    <!-- 弹出层一般放在最外层 -->
    <ImportEexcel :show-excel-dialog.sync="showExcelDialog" :upload-success="getEmployeeList" />
    <!-- 分配角色弹框 -->
    <el-dialog title="分配权限" :visible.sync="showRoleList">
      <el-checkbox-group v-model="roleIds">
        <el-checkbox v-for="item in RoleList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
      </el-checkbox-group>
      <el-row slot="footer" justify="center" type="flex">
        <el-col :span="6">
          <el-button type="primary" @click="btnOk">确定</el-button>
          <el-button @click="showRoleList=false">取消</el-button>
        </el-col>

      </el-row>

    </el-dialog>

  </div>
</template>

<script>
import ImportEexcel from './components/import-excel.vue'
// 引入表格文件
import { getEmployeeList, getExeclList, deleUser, getEmployeeRole, assignRole, getEmployeeDetail } from '@/api/employee'
// 数据渲染
import { getDpartment } from '@/api/department'
// 引入树形结构
import { transListToTreeData } from '@/utils/index'
import FileSaver from 'file-saver'
export default {
  name: 'Employee',
  components: {
    ImportEexcel
  },
  data() {
    return {
      currentUserId: null, // 用来记录当前点击的用户id
      showExcelDialog: false, // 导出入弹出层显示
      showRoleList: false, // 显示角色勾选弹层
      total: 0,
      RoleList: [], // 角色勾选列表
      list: [], // 表格数据
      depts: [], // 树形控件数据
      roleIds: [], // 双向绑定弹层复选框
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      queryParams: {
        departmentId: null,
        page: 1,
        pagesize: 10,
        keyword: ''
      }
    }
  },
  created() {
    this.getDpartment()
    this.getEmployeeList()
  },
  methods: {
    async getDpartment() {
      this.depts = transListToTreeData(await getDpartment(), 0)
      // 设置选中节点
      this.queryParams.departmentId = this.depts[0].id
      // 再进行更新
      this.$nextTick(() => {
        this.$refs.deptTree.setCurrentKey(this.queryParams.departmentId)
      })
      this.getEmployeeList()
    },
    // 获取数据
    async getEmployeeList() {
      const { rows, total } = await getEmployeeList(this.queryParams)
      this.list = rows
      this.total = total
    },
    changePage(newPage) {
      this.queryParams.page = newPage
      // 赋值完再获取新的数据
      this.getEmployeeList()
    },
    seletNode(node) {
      this.queryParams.departmentId = node.id // 重新记录了参数
      this.queryParams.page = 1 // 设置第一页
      this.getEmployeeList()
    },
    changeValue() {
      // 单位时间内只执行最后一次
      // this的实例上赋值了一个timer的属性
      clearTimeout(this.timer) // 清理上一次的定时器
      this.timer = setTimeout(() => {
        this.queryParams.page = 1
        this.getEmployeeList()
      }, 30)
    },
    async getExecl() {
      const result = await getExeclList()
      // console.log(res)
      FileSaver.saveAs(result, '员工信息表.xlsx')
    },
    // 删除员工
    async confirmDel(id) {
      await deleUser(id)
      // 重新获取数据
      if (this.list.length === 1 && this.queryParams.page > 1) this.queryParams.page--
      this.getDpartment()
      this.$message.success('删除角色成功')
    },
    // 员工分配权限
    async btnRole(id) {
      this.showRoleList = true
      this.RoleList = await getEmployeeRole()
      // console.log(this.RoleList)
      this.currentUserId = id
      const { roleIds } = await getEmployeeDetail(id)
      this.roleIds = roleIds
      this.showRoleList = true // 调整顺序
    },
    async btnOk() {
      await assignRole({
        id: this.roleIds,
        roleIds: this.roleIds
      })
      this.$message.success('分配角色成功')
      this.showRoleList = false
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
  }
}

</style>
